package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.mapper.BackPermissionMapper;
import com.neuedu.pojo.BackPermission;
import com.neuedu.pojo.RoleBackPermission;
import com.neuedu.pojo.User;
import com.neuedu.service.IBackPermissionService;
import com.neuedu.service.IRoleBackPermissionService;
import com.neuedu.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wgq
 * @since 2020-09-25
 */
@Service
public class BackPermissionServiceImpl extends ServiceImpl<BackPermissionMapper, BackPermission> implements IBackPermissionService {
    @Resource
    IRoleBackPermissionService roleBackPermissionService;
    @Resource
    IUserService userService;
    @Resource
    IBackPermissionService backPermissionService;


    @Override
    public List<String> userPermissionListValidate(int userId) {
        List<BackPermission> backPermissionList = backPermissionService.list();

        User user = userService.getById(userId);
        QueryWrapper<RoleBackPermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", user.getUserType());
        RoleBackPermission roleBackPermission = roleBackPermissionService.getOne(wrapper);
        String[] permissions = roleBackPermission.getPermissionId().split(",");
        List<String> result = new ArrayList<>();
        for (String permission : permissions) {
            String uri = "";
            BackPermission perm = null;
            do {
                perm = getBP(backPermissionList, Integer.parseInt(permission));
                uri = perm.getUrl() + uri;
                permission = perm.getParent();
            } while (!permission.equals("0"));
            result.add(uri);
        }
        return result;
    }

    BackPermission getBP(List<BackPermission> backPermissionList, int id) {
        for (BackPermission bp : backPermissionList) {
            if (bp.getId() == id) {
                return bp;
            }
        }
        return null;
    }
}
